from .colors import *
from .mask import *
from .raster_settings import *
from PIL import ImageSequence
from PIL import Image
import os


def divide_frames(seq_image: str) -> list[str]:
    sponge_thumb = Image.open(seq_image)
    seq_image_name = os.path.splitext(seq_image)[0]
    res = []
    for index, image in enumerate(ImageSequence.Iterator(sponge_thumb)):
        image: Image.Image
        image.convert("RGBA")
        image.save(f"build/{seq_image_name}_frame_{index}.png")
        res.append(f"{seq_image_name}_frame_{index}.png")
    return res


def rasterlize_frames(frame_names: list[str], raster: RasterSetting) -> Image.Image:
    frames: list[Image.Image] = []
    for index, frame_file in enumerate(frame_names):
        frame_image = Image.open("build/"+frame_file).convert("RGBA")
        masked = draw_mask(frame_image, RGBA_TRANSPARENT, raster.raster_a, raster.raster_d, index)
        frame_name = os.path.splitext(frame_file)[0]
        masked.save(f"build/masked_{frame_name}.png")
        frames.append(masked)

    result = Image.new("RGBA", frames[0].size, RGBA_TRANSPARENT)
    for frame in frames:
        result = Image.alpha_composite(result, frame)
    # result.save("sponge_thumb.png")
    return result


def generate_rasterlized_cartoon(background: Image.Image, raster: RasterSetting, file_name="") -> list[Image.Image]:
    frame_length = raster.raster_d//raster.raster_a
    frames = []
    for index in range(frame_length):
        mask = draw_mask(Image.new("RGBA", background.size, RGBA_TRANSPARENT), RGBA_BLACK,
                         raster.raster_a, raster.raster_d, index)
        mask.save(f"build/mask_{file_name}_{index}.png")
        frames.append(Image.alpha_composite(background, mask))
    return frames
